﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;
using System.IO;

namespace TfsExtensions.Build.Activities
{
    public sealed class InvokeBuildAssembler : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> SandcastleProductionToolsFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> WorkingFolderName { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleConfigFilename { get; set; }

        [RequiredArgument]
        public InArgument<string> ManifestFilename { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            // this activity runs following command.
            // <Exec Command="&quot;$(BuildAssemblerEXE)&quot; /config:$(WorkingFolderName)\$(SandcastleConfigFilename) $(WorkingFolderName)\$(ManifestFilename)" />

            var workingFolderName = this.WorkingFolderName.Get(context);
            var sandcastleConfigFilename = this.SandcastleConfigFilename.Get(context);
            var manifestFilename = this.ManifestFilename.Get(context);

            var exeFileName = string.Format(@"{0}\BuildAssembler.exe", this.SandcastleProductionToolsFolder.Get(context));
            var sandcastleWorkingFolderPath = "/config:\"" + string.Format(@"{0}\{1}", workingFolderName, sandcastleConfigFilename) + "\"";
            var manifestWorkingFolderPath = "\"" + string.Format(@"{0}\{1}", workingFolderName, manifestFilename) + "\"";
            if (!File.Exists(string.Format(@"{0}\{1}", workingFolderName, sandcastleConfigFilename)))
            {
                LogHelper.LogError(context, "Config file not found at " + workingFolderName);
                return;
            }

            if (!File.Exists(string.Format(@"{0}\{1}", workingFolderName, manifestFilename)))
            {
                LogHelper.LogError(context, "Manifest file not found at " + workingFolderName);
                return;
            }

            var arguments = string.Format("{0} {1}", sandcastleWorkingFolderPath, manifestWorkingFolderPath);

            try
            {
                InvokeCommand.ExecuteCommand(context, exeFileName, arguments);
            }
            catch(Exception ex)
            {
                LogHelper.LogError(context, ex.Message);
                throw;
            }
        }
    }
}
